package com.sy.olddriver.utils;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.commons.dbutils.QueryRunner;

import java.sql.Connection;
import java.sql.SQLException;

public class DBUtils {
    private static DruidDataSource ds = new DruidDataSource();
    private static ThreadLocal<Connection> curCon = new ThreadLocal<>();

    private DBUtils() {

    }

    static {
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost:3306/olddriver");
        ds.setUsername("root");
        ds.setPassword("");
    }

    /**
     * 获取数据库连接对象
     *
     * @return
     */
    public static Connection getConnection() {
        Connection con = curCon.get();
        if (con == null) {
            try {
                con = ds.getConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            curCon.set(con);
        }
        return con;
    }

    public static QueryRunner getRunner() {
        QueryRunner runner = new QueryRunner(ds);
        return runner;
    }

    public static void beginTx() {
        Connection connection = getConnection();
        try {
            connection.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void endTx() {
        Connection connection = getConnection();
        try {
            connection.commit();
            connection.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                    curCon.set(null);
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    public static void rollBack() {
        Connection connection = getConnection();
        try {
            connection.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                    curCon.set(null);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
